<template>
	<Layout :showBack="false" tabbar :innerBottom="false">
		<template #title>消息</template>
		<ConversationList v-if="imStore.initialized && init" :sessionList="sessionList" />
	</Layout>
	<LoginPopup></LoginPopup>
</template>

<script lang="ts" setup>
	import ConversationList from './conversation-list/index.vue';
	import type { NimKitCoreTypes } from '@xkit-yx/core-kit';
	import type { IMMessage } from '@xkit-yx/im-store';
	import { setTabbar } from '@/utils/wx';
	import { ref, watchEffect } from 'vue';
	import { autorun } from 'mobx';
	import { deepClone } from '@/im/util';
	import { onShow } from '@dcloudio/uni-app'
	import { trackInit } from '@/im/reporter'
	import { setContactTabUnread, setTabUnread } from '@/im/msg';
	import { useImStore, useAuthStore } from '@/stores';
	import type { AnyObj } from '@/types/global';
	setTabbar({ selected: 3 });

	const authStore = useAuthStore();

	const init = ref(false);
	const sessionList = ref<AnyObj[]>([]);

	const imStore = useImStore();

	function getSessionList() {
		return new Promise((resolve) => {
			// @ts-ignore
			const account = uni.$$nimAuth.account;
			// @ts-ignore
			uni.$$nim.nim.cloudSession.queryCloudSessionList({}).then(res => {
				console.log('sessionsABC555', res);
				// @ts-ignore
				const list = res.sessionList.map((item, index) => {
					const { from, to } = item.lastMsgInfo?.lastMsg ?? {};

					return {
						ack: item.updateTime,
						scene: item.lastMsgInfo?.lastMsg.scene ?? 'p2p',
						id: `${item.sessionId}`,
						renderKey: `${item.sessionId}${index}`,
						to: from === account ? to : from,
						lastMsg: item.lastMsgInfo?.lastMsg ?? {
							time: 0,
							type: '',
							body: '',
							status: '',
						},
						updateTime: item.updateTime,
						unread: 0,
						isMute: false,
						beMentioned: false,
						...item
					}
				});
				resolve(list);
			})
		});
	}

	watchEffect(() => {
		console.log('imStore.initialized', imStore.initialized);
		if (imStore.initialized) {
			trackInit('ConversationUIKit');
			getSessionList().then(list => {
				// @ts-ignore
				sessionList.value = list;
				init.value = true;
			})
		}
	});

	function success() { }



	async function tapGetSession() {
		// console.log('sessionsABC444', uni.$$nim.nim.session.getAllSessions());

	}



	onShow(() => {
		if (!authStore.isLogin) {
			authStore.show();
		}
		// 重置选中会话
		// @ts-ignore
		uni.$UIKitStore?.uiStore.selectSession('')
		setTabUnread()
		setContactTabUnread()
	})
</script>

<style scope lang="scss">
	@import '@/im/styles/common.scss';
</style>